package com.rd.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.rd.common.CommonResult;
import com.rd.common.vo.GrantMenuFormData;
import com.rd.common.vo.GrantRoleFormData;
import com.rd.common.vo.PageBean;
import com.rd.mapper.SysMenuMapper;
import com.rd.pojo.*;
import com.rd.service.SysRoleMenuService;
import com.rd.service.SysRoleService;
import com.rd.service.SysUserRoleService;
import com.rd.service.SysUserService;
import com.rd.util.ResultUtil;
import io.netty.util.internal.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.*;

@RestController
@RequestMapping("/sys/role")
@Slf4j
public class SysRoleController {

    @Resource
    SysRoleService sysRoleService;

    @GetMapping("/allRoles")
    @PreAuthorize("hasAuthority('system:role:query')")
    public CommonResult allRoles() {
        List<SysRole> roleList = sysRoleService.list();
        return ResultUtil.buildSuccess(roleList);
    }

    @Resource
    SysMenuMapper sysMenuMapper;
    @PostMapping("/list")
    /**拥有查询权限才可以访问方法*/
    @PreAuthorize("hasAuthority('system:user:query')")
    public CommonResult userlist(@RequestBody PageBean pageBean) {
        //mybatis-plus提供一个page方法帮助分页
        // import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
        Page<SysRole> page = new Page<>
                (pageBean.getPageNum(), pageBean.getPageSize());

        //新增一个查询条件
        QueryWrapper<SysRole> queryWrapper = new QueryWrapper<>();
        String queryValue = pageBean.getQuery().trim();
        log.info("queryValue={}", queryValue);
        //like是模糊查询  where name like '%queryValue%'
        queryWrapper.like(!StringUtil.isNullOrEmpty(queryValue), "name", queryValue);
        IPage<SysRole> iPage = sysRoleService.page(page, queryWrapper);
        List<SysRole> roleList = iPage.getRecords();
        for (SysRole sysRole : roleList) {
            List<SysMenu> menuList = sysMenuMapper.selectMenuByRoleId(sysRole.getId());
            sysRole.setSysMenuList(menuList);
        }
        long total = iPage.getTotal();
        Map<String, Object> map = new HashMap<>();
        map.put("roleList", roleList);
        map.put("total", total);
        return ResultUtil.buildSuccess(map);
    }

    @PostMapping("/addRole")
    @PreAuthorize("hasAuthority('system:role:add')" + "||" + "hasAuthority('system:role:edit')")
    public CommonResult addRole(@RequestBody SysRole sysRole) {
        if (StringUtil.isNullOrEmpty(String.valueOf(sysRole.getId())) || sysRole.getId() == -1) {
            //新增
            sysRole.setCreateTime(new Date());
            boolean flag = sysRoleService.save(sysRole);
            return flag ? ResultUtil.buildSuccess("添加成功!") : ResultUtil.buildError("添加失败!");
        } else {
            sysRole.setUpdateTime(new Date());
            boolean flag = sysRoleService.updateById(sysRole);
            return flag ? ResultUtil.buildSuccess("修改成功!") :
                    ResultUtil.buildError("修改失败!");
        }
    }

    /*验证角色名是否重复*/
    @GetMapping("/checkRoleName/{name}")
    @PreAuthorize("hasAuthority('system:role:query')")
    public CommonResult checkRoleName(@PathVariable("name") String name) {
        SysRole sysRole = sysRoleService.getRoleByName(name);
        return sysRole == null ? ResultUtil.buildSuccess("此角色名可以使用") :
                ResultUtil.buildError("此角色名已经被注册");
    }

    /*验证权限字符是否重复*/
    @GetMapping("/checkRoleCode/{code}")
    @PreAuthorize("hasAuthority('system:role:query')")
    public CommonResult checkRoleCode(@PathVariable("code") String code) {
        QueryWrapper<SysRole> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("code", code);
        SysRole sysRole = sysRoleService.getOne(queryWrapper);
        return sysRole == null ? ResultUtil.buildSuccess("此权限字符可以使用!") :
                ResultUtil.buildError("此权限字符已经被注册!");
    }

    /*根据用户id获取用户详细信息*/
    @GetMapping("/getRole/{RoleId}")
    @PreAuthorize("hasAuthority('system:user:query')")
    public CommonResult getRole(@PathVariable("RoleId") Long roleId) {
        SysRole sysRole = sysRoleService.getById(roleId);
        return ResultUtil.buildSuccess(sysRole);
    }

    @Resource
    SysUserRoleService sysUserRoleService;
    @Resource
    SysRoleMenuService sysRoleMenuService;

    @Transactional
    @PostMapping("/deleteRole")
    @PreAuthorize("hasAuthority('system:role:delete')")
    public CommonResult deleteRole(@RequestBody Long[] ids) {
        log.info("需要逻辑删除用户id:{}", Arrays.toString(ids));
        //1---->先从 sys_user_role表中删除这个用户记录
        QueryWrapper<SysUserRole> queryWrapper = new QueryWrapper<>();
        // where role_id in(1,2,3)
        queryWrapper.in("role_id", ids);
        sysUserRoleService.remove(queryWrapper);
        //2---->从 sys_role_menu表中删除这个用户记录
        QueryWrapper<SysRoleMenu> queryWrapper2 = new QueryWrapper<>();
        // where role_id in(1,2,3)
        queryWrapper2.in("role_id", ids);
        sysRoleMenuService.remove(queryWrapper2);
        //3---->再删除 sys_role表中的数据
        sysRoleService.removeByIds(Arrays.asList(ids));
        return ResultUtil.buildSuccess("删除成功");
    }

    @Transactional
    @PostMapping("/grantRole")
    @PreAuthorize("hasAuthority('system:role:menu')")
    public CommonResult deleteUser(@RequestBody GrantRoleFormData formData) {
        log.info("formData={}", formData);
        //先删除这个用户角色delete from sys_user_role where role_id=?
        sysUserRoleService.remove(new QueryWrapper<SysUserRole>().eq("role_id", formData.getId()));
        //先删除这个角色权限delete from sys_role_menu where role_id=?
        sysRoleMenuService.remove(new QueryWrapper<SysRoleMenu>().eq("role_id", formData.getId()));
        //批量插入
        List<SysUserRole> list = new ArrayList<>();
        if (Objects.nonNull(formData.getCheckedRoles())) {
            for (Long roleId : formData.getCheckedRoles()) {
                SysUserRole sysUserRole = new SysUserRole();
                sysUserRole.setUserId(formData.getId());
                sysUserRole.setRoleId(roleId);
                list.add(sysUserRole);
            }
        }
        //批量插入
        List<SysRoleMenu> list2 = new ArrayList<>();
        if (Objects.nonNull(formData.getCheckedRoles())) {
            for (Long roleId : formData.getCheckedRoles()) {
                SysRoleMenu sysRoleMenu = new SysRoleMenu();
                sysRoleMenu.setRoleId(formData.getId());
                sysRoleMenu.setMenuId(roleId);
                list2.add(sysRoleMenu);
            }
        }
        sysUserRoleService.saveBatch(list);
        sysRoleMenuService.saveBatch(list2);
        return ResultUtil.buildSuccess("角色分配成功");
    }

    @Transactional
    @PostMapping("/grantMenu")
    @PreAuthorize("hasAuthority('system:role:menu')")
    public CommonResult grantMenu(@RequestBody GrantMenuFormData formData) {
        log.info("formData={}", formData);
        //先删除这个权限角色 delete from sys_role_menu where role_id=?
        sysRoleMenuService.remove(new QueryWrapper<SysRoleMenu>
                ().eq("role_id", formData.getId()));
        //批量插入
        List<SysRoleMenu> list = new ArrayList<>();
        if (Objects.nonNull(formData.getCheckedMenus())) {
            for (Long MenuId : formData.getCheckedMenus()) {
                SysRoleMenu sysRoleMenu = new SysRoleMenu();
                sysRoleMenu.setRoleId(formData.getId());
                sysRoleMenu.setMenuId(MenuId);
                list.add(sysRoleMenu);
            }
        }
        sysRoleMenuService.saveBatch(list);
        return ResultUtil.buildSuccess("权限分配成功");
    }
}
